package com.xyz.graph.handler;

import com.xyz.graph.util.GraphUtil;
import com.xyz.graph.util.GremlinUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tinkerpop.gremlin.driver.Client;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.schema.JanusGraphManagement;
import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
@Slf4j
public class PreStartDoThing {
    public static GraphTraversalSource graphTraversalSource;
    public static Client jClient;
    public static JanusGraphManagement mgmt;
    public static String props;

//    public static String getClientip() {
//        return clientip;
//    }
//
//    @Value("${clientip:12.39.103.156}")
//    public void setClientip(String clientip) {
//        PreStartDoThing.clientip = clientip;
//    }
//
//    public static String clientip;

    @PostConstruct
    public void init(){
//        log.info("初始化图数据库连接,"+System.getProperty("os.name"));
//
//        //get graphsource
//        Cluster cluster = GremlinUtil.cluster("127.0.0.1", 8182, JanusGraphIoRegistry.getInstance());
//        graphTraversalSource = GremlinUtil.source(cluster);
    }

    @PreDestroy
    public void destory(){
//        try {
//            graphTraversalSource.close();
//        } catch (Exception e) {
//            log.error("关闭连接错误："+e);
//        }

    }

    public static GraphTraversalSource getG(){
        if(graphTraversalSource == null){
//            Graph graph = EmptyGraph.instance();
//            GraphTraversalSource g = null;

            //get graphsource
            Cluster cluster = GremlinUtil.cluster("127.0.0.1", 8182, JanusGraphIoRegistry.getInstance());
            graphTraversalSource = GremlinUtil.source(cluster);
        }
        return graphTraversalSource;
    }

    //图管理连接,弃用
    public static Client getClient(){
        if(PreStartDoThing.jClient==null){
            //图管理连接

        }

        return PreStartDoThing.jClient;
    }

    public static JanusGraphManagement getJanusGraphManagement(){

        if(mgmt==null){
            GraphUtil graphUtil = new GraphUtil();
            JanusGraph graph = graphUtil.buildGraphMgntByFile(null);
            mgmt = graph.openManagement();
        }
        return mgmt;
    }

}
